<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
	<th:block th:include="include :: header('周报总结')" />
	<th:block th:include="include :: businessCSS" />
	<style type="text/css">
		.layui-card-header.layuiadmin-card-header-auto{
			box-shadow:none;
		}
	</style>
</head>
<body class="no-skin">
<div class="main-container" id="main-container">
	<div class="main-content">
		<form class="layui-form head-form">
		    <div class="north">
                <th:block th:include="include :: business_btn" />
	        	<th:block th:include="include :: business_tpl('top')" />
	    	</div>
		    <div class="mid-content">
		        <table class="layui-hide" id="dhtable" lay-filter="ftable"></table>
		    </div>
			<th:block th:include="include :: pageFooter" /> 
		</form>
	</div>
</div>
<th:block th:include="include :: footer" />
<th:block th:include="include :: businessJS" />
<th:block th:include="include :: businessTableBtn" />
<th:block th:include="include :: inlineJS" />
<!-- 后台传回通用参数-->
<script th:inline="javascript">
    /*<![CDATA[*/
    var isBuser = [[${isBuser}]],
    	nowTimeStr = [[${nowTimeStr}]];
    /*]]>*/
</script>
<script type="text/javascript">
nowTimeStr = (new Date(Date.parse(nowTimeStr.replace(/-/g,"/"))).getTime())/1000;
var $,layer,form,table,laydate,element;//定义layui模块
eachFields();//明细表格中的字段遍历
//拼接弹出框表单
var layui_col_sm = '',
	requiredStr = '',
	hiddenStr = '',
	classStr = '',
	fieldFrontEdit = '',
	fieldFrontEditClass = '',
	fTotalJeExtend = '',
	overkm = unoverkm = btkm = cbbl = 0,
	boxContent = '<div class="layuiadmin-card-header-auto layui-card-header" style="padding-right: 20px;border:none;">'; 
	
$.each(gridColumns.dictionaryForPageFieldList, function(i, v){		
	if(v.fields == 'fTotalJe'){
		fTotalJeExtend = v.fieldFrontExtend3;
	}
	// if(v.fields == 'iid' || v.fieldFrontHidden == 'true' || v.fieldFrontTop == 7){
	if(v.fields == 'iid' || v.fieldFrontTop == 7){
		hiddenStr += '<input type="hidden" id="'+v.fields+'" class="layer-form">';
		return;
	}
	if(v.fieldFrontTopSize == 1){
		layui_col_sm = "layui-col-sm4";
	}else if(v.fieldFrontTopSize == 2){
		layui_col_sm = "layui-col-sm8";
	}else{
		layui_col_sm = "layui-col-sm12";
	}
	if(v.fieldFrontType == 't_decimal' && v.fields != 'fYxGs')layui_col_sm = "layui-col-sm3";
	if(v.fieldFrontRequired){requiredStr = '<font class="f_red">*</font>';}else{requiredStr = '';}		//是否必填
	if(!v.fieldFrontEdit){fieldFrontEdit = 'readonly';fieldFrontEditClass = 'canntEdit'}else{fieldFrontEdit = '';fieldFrontEditClass = '';}			//是否可编辑
	
	if(v.fields == 'fTotalJe')boxContent += '<div class="layui-inline margin_r0 layui-col-sm3"><label class="layui-form-label"></label><div class="layui-input-block"></div></div>';
	boxContent += '<div class="layui-inline margin_r0 '+layui_col_sm+'">';
	boxContent += '<label class="layui-form-label">'+requiredStr+v.fieldName+'：</label><div class="layui-input-block">';
	switch(v.fieldFrontType){
		case 't_text':
			boxContent += '<input type="text" id="'+v.fields+'" class="layui-input layer-form '+fieldFrontEditClass+'" autocomplete="off" '+fieldFrontEdit+'>';
		break;
		case 't_textarea':
			boxContent += '<textarea id="'+v.fields+'" class="layui-textarea layer-form"></textarea>';
		break;
		case 't_decimal':
			if(v.fields == 'fBKM' || v.fields == 'fRKM'){
				classStr = ' class="layui-input layer-form kmField '+fieldFrontEditClass+'"';
			}else{
				classStr = ' class="layui-input layer-form '+fieldFrontEditClass+'"';
			}
			boxContent += '<input type="number" id="'+v.fields+'" min="0" onblur="gtZero(this)" '+classStr+' autocomplete="off" lay-verify="number" '+fieldFrontEdit+'>';
		break;
		case 't_date':
		case 't_datetime':
		case 't_year':
			boxContent += '<input type="text" id="'+v.fields+'" autocomplete="off" class="layui-input t_date layer-form" readonly=""><i class="dhicon dh-calendar icon_date_business"></i>';
		break;
		case 't_buttontext':
			boxContent += '<input type="text" id="'+v.fields+'" class="layui-input buttontext layer-form" readonly=""><i class="layui-icon layui-icon-more getMore" onclick="getMore(\''+v.fields+'\',null,\''+v.fieldName+'\',null,false,true);" gettype="'+v.fields+'"></i>';
		break;
	}
	boxContent += '</div></div>';
	if(v.fields == 'fBtJe')boxContent += '<div class="layui-inline margin_r0" style="width:100%;"><label style="float:right;height: 30px;line-height: 24px;display: block;padding: 4px 0px;">本月已累计行驶公里数为：<span style="color:red;" id="overkm"> 计算中 </span>；（除去本次累计：<span style="color:red;" id="unoverkm"></span>）；您的车补公里总数为：<span style="color:red;" id="btkm"></span>；</label></div>';
})
boxContent += hiddenStr+'</div>';	
layui.use(['laydate', 'table','form','layer','jquery','util','element'], function () {
 	$ = layui.$,layer = layui.layer,form = layui.form,table = layui.table,laydate = layui.laydate,util = layui.util,element=layui.element;
 	beforeInit();//表单初始化之前的动作集合
 	$.get(moduleUrl+"/listbynid?nid="+nid,function(data){
		$.each(data.data,function(k,v){
			dataStr.push(v);
		});
		initTable();//初始化表格
	});
	//头部event事件
	table.on('toolbar(ftable)', function(obj){
		var checkStatus = table.checkStatus('dhtable');
	    switch(obj.event){
	    	case 'addBtn':
	    		if($("#dFinishDate").val()){
	    			openDetail('新增总结',boxContent)
	    		}else{
	    			layer.msg("请先选择总结日期！");return false;
	    		}
	    	break;
	    	case 'deleteBatch':
	    		tableDeleteBatch('dhtable', listData, checkStatus);
	    	break;
	    	case 'fieldSet':
	    		filedSet(moduleTable+'_EditPage202109');
         	break;
			case 'tableFull'://表格展开
				$('.north .layui-form').hide();
				table.reload('dhtable',{
					defaultToolbar: [{title:'收缩',layEvent:'tableShrink',icon:'layui-icon-screen-restore'}],
					height: $(window).height()-$('.north').height()-60<300?'300':$(window).height()-( $('.north').height()+$('.south').height()+12)
				});
			break;
			case 'tableShrink'://表格收缩
				$('.north .layui-form').show();
				table.reload('dhtable',{
					defaultToolbar: [{title:'展开',layEvent:'tableFull',icon:'layui-icon-screen-full'}],
					height: $(window).height()-$('.north').height()-60<300?'300':$(window).height()-( $('.north').height()+$('.south').height()+12)
				});
			break;
	    	case 'importBtn':
	    		$.tablelist.importExcel('dhtable',importFields, table.cache.dhtable, moduleTable, decimalObj);
         	break;
	    };
	});
	monitorSort();//监听排序——重载赋值渲染
	//监听行双击事件
	table.on('rowDouble(ftable)', function(obj){
		openDetail('查看总结',boxContent,obj.data,$(obj.tr.selector).attr('data-index'));
	});
	//明细弹出框
	function openDetail(title,content,detailData='',rowid){
		layer.open({
			type: 1,
			area: [($(window).width() - 250)+'px', ($(window).height() - 200)+'px'],
			fix: false,//不固定
			offset: '10%',//距离顶部
			maxmin: true,//最大最小化
			shade: 0.3,//遮罩
			title: title,
			content: content,
			btn: ['确定','关闭'],
			shadeClose: true,// 弹层外区域关闭
			success: function(layero, index){
				console.log(isBuser, $("#activeFlow").val())
				if($("#activeFlow").val().toLowerCase() == 'flowzd')$("#vFReply").parent().parent().css('display','none');			//制单隐藏上级批复
				//非制单状态，制单人查看（只读）
				if(isBuser && $("#activeFlow").val().toLowerCase() != 'flowzd'){
					$(".layui-card-header .layer-form").attr('disabled',true).addClass("canntEdit");
					$(".getMore").remove();
				}		
				//非制单状态，非制单人（上级）查看（只读）
				if(!isBuser && $("#activeFlow").val().toLowerCase() != 'flowzd'){
					$(".layui-card-header .layer-form").attr('disabled',true).addClass("canntEdit");
					$("#vFReply").attr('disabled',false).removeClass("canntEdit");
					$(".getMore").remove();
				}
				//查看表单字段赋值
				if(detailData){
					$.each(detailData,function(i,v){
						if(i=='fTKM')console.log(v)
						if(v || i=='fTKM' || i=='fBtJe')$("#"+i).val(v);
					})
				}
				//有效工时（填写数字按小时核算，最少0.5填写）
				$("#fYxGs").attr('step','0.5').removeAttr("onblur");
				$("#fYxGs").blur(function(){
					if($(this).val() < 0){
						$(this).val("");
					}else if($(this).val() > 0){
						$(this).val(Math.floor($(this).val() * 2)/2);	
					}
				})
				//报销字段
				var arr = fTotalJeExtend.split('+');
				for(var i in arr){
					$("#"+arr[i]).addClass("fyField");
			  	}
				//报销费用合计
				$(".fyField").change(function(){
					var totalJe = 0;
					$(".fyField").each(function(i,v){
						totalJe += Number($(v).val());
					})
					$("#fTotalJe").val(totalJe);
				})
				//除当前明细外的，已车补公里
				var otherkm = talkm = 0;
				if(listData.length > 0){
					$.each(listData,function(i,v){
						otherkm += Number(v.fTKM?v.fTKM:0);
					})	
				}
				talkm = otherkm;
				if(rowid)otherkm -= Number($("#fTKM").val());
				otherkm = otherkm < 0 ?0:otherkm;

				getkm($("#dFinishDate").val(),otherkm,talkm);
				
				//获取车补公里数及比例
				$.post('../../base/baseinfo/linevid',{vid:$("#aUser").val(),vtype:'cbjebl'},function(res){
					btkm = cbbl = 0;
					if(res.code == 0){
					    btkm = res.data.vAccount?res.data.vAccount:0;
					    cbbl = res.data.fvalue?res.data.fvalue:0;
				    }
			    	$("#btkm").html(btkm);
				});

				//计算车补金额
				$(".kmField").blur(function(){
					var cbJe = 0;
			        var t2=$("#fRKM").val();
			        var t1=$("#fBKM").val();
				    if(t2 && t1){
				        if(t2-t1<0){layer.alert("‘返回公里数’必须大于‘初始公里数’！", {icon: 2});return false;}
				        var TKM=t2-t1;
				        if(rowid){
				            if(unoverkm + TKM > btkm){
				                TKM = TKM - (unoverkm + TKM - btkm);//本次超出补贴公里数，只计算为本次超出部分公里数；
				            }
				        }else{
				            if(overkm + TKM > btkm){
				                TKM = TKM - (overkm + TKM - btkm);//本次超出补贴公里数，只计算为本次超出部分公里数；
				            }
				        }
				        if(TKM < 0)TKM = 0;
				        $('#fBtJe').val((cbbl*TKM).toFixed(2));
				        $('#fTKM').val(TKM);
				    }
				})
				$.each(gridColumns.dictionaryForPageFieldList,function(k,v){
					if(v.fieldFrontType=="t_dropdown" && !gridColumns.readOnly && v.fieldFrontSave!=v.fieldFrontShow && !!v.fieldMatched && v.fieldFrontEdit)$('#'+v.fieldMatched.split(',')[0]).val($('#'+v.fields).val());//表头下拉框的隐藏框赋值（非只读）
					/* if((v.fieldFrontType=="t_date" || v.fieldFrontType=="t_datetime" || v.fieldFrontType=="t_year") && v.fieldFrontEdit && !gridColumns.readOnly){//表头时间控件渲染（非只读）
						laydate.render({elem:'#'+v.fields,type:v.fieldFrontType.substring(2,v.fieldFrontType.length),trigger:'click'});
					} */
				});
			 	layui.element.render();
			},
			btn1: function(index, layero){
				var formVal = {};
				$.each($('.layer-form'),function(i,v){
					var formField = $(v).attr('id');
						formVal[formField] = $(v).val();
				})
				if(detailData){
					listData[rowid] = formVal;
					//上级批复保存
					if(!isBuser && $("#activeFlow").val().toLowerCase() != 'flowzd'){
						var pd=[];
						pd.push({"guid":formVal.guid,"vFReply":formVal.vFReply})
						var postData = {'infoItems':JSON.stringify(pd)};//转化为json字符串格式
					    $.operate.post(moduleUrl+'/ffpost', postData, function(res){
					        if(res.code != 0){
					        	layer.msg('上级批复保存失败！');
					        }
					    });
					}
				}else{
					if(listData.length > 0){
	 	    			if(listData[listData.length - 1]['iid']){
	 	    				formVal['iid'] = Number(listData[listData.length - 1]['iid']) + 1;
	 	    			}else{
	 	    				formVal['iid'] = 1;
	 	    			}
	 	    		}else{
	 	    			formVal['iid'] = 1;
	 	    		}
	 	    		listData.push(formVal);
				}
 	    		
 	        	table.reload('dhtable', {data : listData});
 	      		form.render();
 	      		layer.close(index);
			},
			btn2:function(index,layero){
	        	layer.close(index);
			}
		});
	}
})
//数值小于0为空
function gtZero(obj){
	if($(obj).val() < 0)$(obj).val("");
}
//获取已使用公里数
function getkm(zjDate,otherkm,talkm){
	var datearr = zjDate.split('-');
	var dFinishDate = datearr[0]+'-'+datearr[1];
	$.post('getkm',{dFinishDate:dFinishDate,aUser:$("#aUser").val(),nid:$("#nid").val()},function(res){
		$("#overkm").html(res.data + Number(talkm));
		$("#unoverkm").html(res.data + Number(otherkm));
		overkm = res.data + Number(talkm);
		unoverkm = res.data + Number(otherkm);
	});
}

</script>
</body>
</html>